package com.deer.wms.inventory.web;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.deer.wms.base.system.constant.RedisConstants;
import com.deer.wms.base.system.model.Area.AreaInfo;
import com.deer.wms.base.system.model.Cell.CellInfo;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.model.Pack.PackDetail;
import com.deer.wms.base.system.model.Pack.PackDetail2;
import com.deer.wms.base.system.model.Shelf.ShelfInfo;
import com.deer.wms.base.system.service.*;
import com.deer.wms.file.configurer.FileSetting;
import com.deer.wms.intercept.annotation.Authority;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.constant.InventoryConstant;
import com.deer.wms.inventory.model.IDS;
import com.deer.wms.inventory.model.Inventory.*;
import com.deer.wms.inventory.model.combinePallet.BoxResultInsertData;
import com.deer.wms.inventory.model.combinePallet.CombinePalletTask;
import com.deer.wms.inventory.model.move.Move;
import com.deer.wms.inventory.model.stockTake.StockTakeTaskDto;
import com.deer.wms.inventory.service.*;
import com.deer.wms.project.root.annotaiton.MyAnnotation;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.*;
import com.deer.wms.system.manage.model.organization.Organization;
import com.deer.wms.system.manage.service.OrganizationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import jxl.format.CellFormat;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.persistence.Column;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.deer.wms.project.root.util.PageUtils.getStart;

/**
 * Created by 郭靖勋 on 2019/12/18.
 */
@Api(description = "库存信息api接口")
@RestController
@RequestMapping("/inventorys")
public class InventoryController {

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private InventoryTransactService inventoryTransactService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private ItemInfoService itemInfoService;

    @Autowired
    private PackDetailService packDetailService;

    @Autowired
    private CellInfoService cellInfoService;

    @Autowired
    private FileSetting fileSetting;

    @Autowired
    private SerialNoService serialNoService;


    @Autowired
    private ItemBatchService itemBatchService;


    @Autowired
    private CombinePalletTaskService combinePalletTaskService;


    @Autowired
    AreaInfoService areaInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ShelfInfoService shelfInfoService;



    /*
          查询容器中存放的物料
          通过容器编码查询查询容器下的物料编码和名称，库存所属该库位
          */
    @GetMapping("/selectItemByCodes")
    public Result selectItemByCodes(@RequestParam String cellCode, @RequestParam String boxCode) {
        List<Inventory> inventories = inventoryService.selectItemByCodes(cellCode, boxCode);
        return ResultGenerator.genSuccessResult(inventories.get(0));

    }


    /*
        查询容器中存放的物料
        通过容器编码查询查询容器下的物料编码和名称，库存所属该库位
        */
    @GetMapping("/getStock")
    public Result getStockForPda(@RequestParam String cellCode, @RequestParam String boxCode, @RequestParam String itemCode) {
        QueryWrapper<Inventory> qw = Wrappers.query();
        Map<String, Object> map = new HashMap<>();
//        map.put("cell_code", cellCode);
//        map.put("box_code", boxCode);
//        map.put("item_code", itemCode);
        qw.like("cell_code",cellCode);
        qw.like("box_code", boxCode);
        qw.like("item_code", itemCode);
//        List<Inventory> inventories = inventoryService.list(qw.a(map, false));
        List<Inventory> inventories = inventoryService.list(qw);
        return ResultGenerator.genSuccessResult(inventories);
    }


    @PostMapping("/insert")
    public Result add(@RequestBody Inventory inventory) {
        inventoryService.save(inventory);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        inventoryService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Inventory inventory) {
        inventoryService.updateById(inventory);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(Integer id) {
        Inventory inventory = inventoryService.getById(id);
        return ResultGenerator.genSuccessResult(inventory);
    }

    @GetMapping("/getAccept")
    public Result getAccept(Integer id, Integer wareId) {
        Inventory inventory = inventoryService.getAccept(id, wareId);
        return ResultGenerator.genSuccessResult(inventory);
    }




    @GetMapping("/getBoxStock")
    public Result getBoxStock(@RequestParam String boxCode, Integer pickTaskId) {


        List<Inventory> inventories = inventoryService.getBoxStock(boxCode);
        if (inventories.size() == 0) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "未查询到容器：[" + boxCode + "]的库存");
        }
//        if (inventories.size() > 1) {
//            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "容器：" + boxCode + "库存数据不唯一");
//        }
        return ResultGenerator.genSuccessResult(inventories);
    }

    @GetMapping("/area/stock")
    public Result getBoxStock(InventoryCriteria criteria) {
        List<InventorySelectDto> retList = new ArrayList<>();
        List<InventorySelectDto> list = inventoryService.findCanBeOutOfStock(criteria);
        Map<String, List<InventorySelectDto>> collect = list.stream().collect(Collectors.groupingBy(InventorySelectDto::getAreaCode));

        for (String areaCode : collect.keySet()) {
            List<InventorySelectDto> inventorySelectDtos = collect.get(areaCode);
            double sum = 0.0;
            for (InventorySelectDto i : inventorySelectDtos) {
                sum += i.getQuantity() - i.getAllotQuantity() - i.getFreezeQuantity();
            }
            InventorySelectDto inv = new InventorySelectDto();
            BeanUtils.copyBeanProp(inv, inventorySelectDtos.get(0));
            inv.setQuantity(sum);
            retList.add(inv);
        }
        return ResultGenerator.genSuccessResult(retList);
    }

//    @GetMapping("/getStock")
//    public Result getStockForPda(@RequestParam String cellCode, @RequestParam String itemCode, @RequestParam String boxCode) {
//        QueryWrapper<Inventory> qw = Wrappers.query();
////        Map<String, Object> map = new HashMap<>();
////        map.put("cell_code", cellCode);
////        map.put("item_code", itemCode);
////        map.put("box_code", boxCode);
//        if (StringUtils.isNotEmpty(cellCode)) {
//            qw.like("cell_code", cellCode);
//        }
//        if (StringUtils.isNotEmpty(itemCode)) {
//            qw.like("item_code", itemCode);
//        }
//        if (StringUtils.isNotEmpty(boxCode)) {
//            qw.like("box_code", boxCode);
//        }
//        List<Inventory> inventories = inventoryService.list(qw);
//        return ResultGenerator.genSuccessResult(inventories);
//    }

    @GetMapping("/list")
    public Result list(InventoryCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<InventoryDto> groupList = inventoryService.findGroupList(criteria);
        PageInfo pageInfo = new PageInfo(groupList);
        return ResultGenerator.genSuccessResult(pageInfo);

//        Integer pageNum = criteria.getPageNum();
//        criteria.setPageNum(getStart(criteria));
//
//
//        List<InventoryDto> list = inventoryService.findList(criteria);
//        PageInfo pageInfo = new PageInfo(list);
//        pageInfo.setPageNum(pageNum);
//        pageInfo.setTotal(inventoryService.findCount(criteria));
//        return ResultGenerator.genSuccessResult(pageInfo);
    }


    @GetMapping("/vmiList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    public Result vmiList(InventoryCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<InventoryDto> list = inventoryService.vmiList(criteria);

        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }



    @GetMapping("soList")
    public Result soList(InventoryCriteria criteria) {

        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<InventoryDto> list = inventoryService.soList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/checkList")
    public Result checkList(InventoryCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<Inventory> list = inventoryService.checkList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


    @GetMapping("/orderList")
    public Result orderList(InventoryCriteria criteria) {
        List<Inventory> list = inventoryService.orderList(criteria);


        return ResultGenerator.genSuccessResult();

    }



    @Value("${wave.direct}")
    //直发虚仓
    private Integer directId;
    @GetMapping("/straight")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    public Result straight(String itemCode) {
        List<Inventory> inventories = inventoryService.list(new QueryWrapper<Inventory>()
                .in("item_code", itemCode)
                .eq("asn_stock_id", directId)
                .notIn("cell_code", 285000, 285333)
                .orderByDesc("modify_time")
        );
        return ResultGenerator.genSuccessResult(inventories);
    }


    @Value("${wave.start}")
    //直发虚仓
    private Integer start;

   //先发配件
    @GetMapping("/startInv")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    public Result startInv(String itemCode,String tradeNo) {

        List<Inventory> inventories = inventoryService.list(new QueryWrapper<Inventory>()
                .in("item_code", itemCode)
                .eq("erp_area_id", start)
                .notIn("cell_code", 285000, 285333)
                        .eq("mto_no",tradeNo)
                .orderByDesc("modify_time")
        );
        return ResultGenerator.genSuccessResult(inventories);
    }

    @GetMapping("/CellUseTypeList")
    public Result CellUseTypeList(InventoryCriteria criteria) {

        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<InventoryDto> list = inventoryService.findByCellUseType(criteria);

        Iterator it = list.iterator();

        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


    @ApiOperation(value = "库存导入", notes = " 库存导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @PostMapping("/importInventory")
    public Result importInventory(InventoryImport excel, @ApiIgnore @User CurrentUser currentUser) {

        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
        }
        jxl.Workbook billWorkbook = null;
        String msg = "Excel 内容有问题，无法导入！";

        try {
            billWorkbook = jxl.Workbook.getWorkbook(excel.getModel().getInputStream());
            jxl.Sheet billSheet = billWorkbook.getSheet(0);

            int rows = billSheet.getRows();

            Integer rowCount = 0;
            for (int i = 1; i < rows; i++) {
                String content = ExcelUtils.getCellString(billSheet, 0, i).trim();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                rowCount++;
            }
            for (int i = 2; i < rowCount + 2; i++) {

                String organizationName = ExcelUtils.getCellString(billSheet, 0, 0).trim();
                Integer organizationId = null;
                QueryWrapper<Organization> qw = new QueryWrapper<>();
                qw.eq("organizationName", organizationName);
                Organization organization = organizationService.getOne(qw);
                organizationId = organization.getOrganizationId();

                String itemName = ExcelUtils.getCellString(billSheet, 1, i).trim();
                String itemCode = null;
                ItemInfo itemInfo = itemInfoService.findBy("item_name", itemName);
                itemCode = itemInfo.getItemCode();

                String packDescribe = ExcelUtils.getCellString(billSheet, 2, i);
                if (packDescribe == null) {
                    msg = "缺少单位！" + packDescribe;
                    throw new Exception();
                }

                PackDetail packDetail = packDetailService.findBy("pack_describe", packDescribe);

                Double quantity = ExcelUtils.getCellDouble(billSheet, 3, i);

                String boxCode = ExcelUtils.getCellString(billSheet, 4, i).trim();
                String lpn = ExcelUtils.getCellString(billSheet, 5, i).trim();

                String cellCode = ExcelUtils.getCellString(billSheet, 6, i);
                if (cellCode == null) {
                    msg = "缺少货位！" + cellCode;
                    throw new Exception();
                }
//                CellInfo cellInfo = cellInfoService.findBy("cellName",cellName);


                Inventory inventory = new Inventory();
                inventory.setWareId(excel.getWareId());
                inventory.setWareName(excel.getWareName());
                inventory.setOrganizationId(organizationId);
                inventory.setOrganizationName(organizationName);
                inventory.setItemCode(itemCode);
                inventory.setItemName(itemName);
                inventory.setBatchName("CSKC");
                inventory.setCellCode(cellCode);
                inventory.setBoxCode(boxCode);
                inventory.setLpn(lpn);
                inventory.setPackDetailId(packDetail.getPackDetailId());
                inventory.setPackDescribe(packDescribe);
                inventory.setQuantity(quantity);
                inventory.setState(0);


                inventoryService.save(inventory);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(CommonCode.WRONG_EXCEL_CONTENT, msg);

        } finally {
            billWorkbook.close();
        }

        return ResultGenerator.genSuccessResult();
    }




    @ApiOperation(value = "库存移动", notes = "库存移动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/move/inventory")
    public Result moveInventory(@RequestBody Move move, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }

        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();

        InventoryTransact inventoryTransact = new InventoryTransact();
//        BeanUtils.copyProperties(moveInventory, inventoryTransact);
        inventoryTransact.setTransactType(InventoryConstant.TRANSACT_TYPE_MOVE);
        inventoryTransact.setItemCode(move.getItemCode());
        inventoryTransact.setItemName(move.getItemName());
        inventoryTransact.setWareId(move.getWareId());
        inventoryTransact.setWareName(move.getWareName());
        inventoryTransact.setToWareId(move.getWareId());
        inventoryTransact.setToWareName(move.getWareName());
        inventoryTransact.setFromCellCode(move.getCellCode());
        inventoryTransact.setToCellCode(move.getToCellCode());
        inventoryTransact.setFromOrganizationId(move.getOrganizationId());
        inventoryTransact.setFromOrganizationName(move.getOrganizationName());
        inventoryTransact.setToOrganizationId(move.getOrganizationId());
        inventoryTransact.setToOrganizationName(move.getOrganizationName());
        inventoryTransact.setFromBatchId(move.getBatchId());
        inventoryTransact.setFromBatchName(move.getBatchName());
        inventoryTransact.setToBatchId(move.getBatchId());
        inventoryTransact.setToBatchName(move.getBatchName());
        inventoryTransact.setFromBoxCode(move.getBoxCode());
        inventoryTransact.setToBoxCode(move.getToBoxCode());
        inventoryTransact.setFromPackDetailId(move.getPackDetailId());
        inventoryTransact.setFromPackDescribe(move.getPackDescribe());
        inventoryTransact.setToPackDetailId(move.getPackDetailId());
        inventoryTransact.setToPackDescribe(move.getPackDescribe());
        inventoryTransact.setFromTransRatio(move.getTransRatio());
        inventoryTransact.setToTransRatio(move.getTransRatio());
        inventoryTransact.setCreateUserId(createUserId);
        inventoryTransact.setCreateUserName(createUserName);
        inventoryTransact.setCreateTime(createTime);
        inventoryTransact.setFromQuantity(move.getQuantity());
        inventoryTransact.setToQuantity(move.getToQuantity());
        int inventoryId = inventoryTransactService.run(inventoryTransact);
        List<String> serialNos = move.getSerialNos();
        if (serialNos != null && serialNos.size() != 0) {
            serialNoService.serialNoRecored(move.getSerialNos(), createUserId,
                    createUserName, null, inventoryId, InventoryConstant.SERIALNO_TRANSFER);
        }
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "查询冻结货位", notes = "查询冻结货位")
    @GetMapping("/findByFreeze")
    public Result findByFreeze(InventoryCriteria criteria) {
        List<Inventory> list = inventoryService.findByCellCode(criteria);
        return ResultGenerator.genSuccessResult(list);
    }

    @ApiOperation(value = "查询解冻货位", notes = "查询解冻货位")
    @GetMapping("/findByRelease")
    public Result findByRelease(InventoryCriteria criteria) {
        List<Inventory> list = inventoryService.findByCellCodeAndState(criteria);
        return ResultGenerator.genSuccessResult(list);
    }

    @ApiOperation(value = "货位冻结", notes = "货位冻结")
    @GetMapping("/freezeCell")
    public Result freezeCell(Integer inventoryId, Double freezeQuantity1, @ApiIgnore @User CurrentUser currentUser) {
        Inventory inventory = inventoryService.getById(inventoryId);
        inventory.setFreezeQuantity(inventory.getFreezeQuantity() + freezeQuantity1);
        inventory.setQuantity(inventory.getQuantity() - freezeQuantity1);

        if (inventory.getQuantity() == 0) {
            inventory.setState(2);
        } else {
            inventory.setState(1);
        }
        inventoryService.updateById(inventory);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "货位批量冻结", notes = "货位批量冻结")
    @GetMapping("/freezeCells")
    public Result freezeCells(String cellCode, Integer wareId, @ApiIgnore @User CurrentUser currentUser) {

        InventoryCriteria criteria = new InventoryCriteria();
        criteria.setCellCode(cellCode);
        criteria.setWareId(wareId);
        List<Inventory> inventorys = inventoryService.findByCellCode(criteria);
        for (Inventory inventory : inventorys) {
            inventory.setFreezeQuantity(inventory.getFreezeQuantity() + inventory.getQuantity());
            inventory.setQuantity(0.0);
            inventory.setState(2);
            inventoryService.updateById(inventory);
        }

        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "货位解冻", notes = "货位解冻")
    @GetMapping("/releaseCell")
    public Result releaseCell(Integer inventoryId, Double freezeQuantity1, @ApiIgnore @User CurrentUser currentUser) {
        Inventory inventory = inventoryService.getById(inventoryId);
        inventory.setFreezeQuantity(inventory.getFreezeQuantity() - freezeQuantity1);
        inventory.setQuantity(inventory.getQuantity() + freezeQuantity1);
        if (inventory.getFreezeQuantity() == 0) {
            inventory.setState(0); //正常
        }
        if (inventory.getQuantity() != 0) {
            inventory.setState(1); //部分冻结
        }
        inventoryService.updateById(inventory);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "货位批量解冻", notes = "货位批量解冻")
    @GetMapping("/releaseCells")
    public Result releaseCells(String cellCode, Integer wareId, @ApiIgnore @User CurrentUser currentUser) {
        InventoryCriteria criteria = new InventoryCriteria();
        criteria.setCellCode(cellCode);
        criteria.setWareId(wareId);
        List<Inventory> inventorys = inventoryService.findByCellCodeAndState(criteria);
        for (Inventory inventory : inventorys) {
            inventory.setQuantity(inventory.getFreezeQuantity());
            inventory.setFreezeQuantity(0.0);
            inventory.setState(0);
            inventoryService.updateById(inventory);
        }

        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "货位锁定", notes = "货位锁定")
    @GetMapping("/lockCell")
    public Result lockCell(String cellCode) {

        InventoryCriteria criteria = new InventoryCriteria();
        criteria.setCellCode(cellCode);
        List<Inventory> inventorys = inventoryService.findByCellCode(criteria);
        if (inventorys.size() > 0) {
            throw new ServiceException(CommonCode.CELL_ERROR);
        }
        CellInfo cellInfo = cellInfoService.findBy("cell_code", cellCode);
        cellInfo.setState("disable");
        cellInfoService.updateById(cellInfo);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "货位解锁", notes = "货位解锁")
    @GetMapping("/unlockCell")
    public Result unlockCell(String cellCode) {

        CellInfo cellInfo = cellInfoService.findBy("cell_code", cellCode);
        cellInfo.setState("enable");
        cellInfoService.updateById(cellInfo);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "同步库存和批次的质检状态 传inventoryId", notes = "同步库存和批次的质检状态 传inventoryId")
    @PostMapping("/synchronization")
    public Result synchronization(BatchData batchData) {
        for (int i = 0; i < batchData.getInventoryIds().size(); i++) {
            Inventory inventory = inventoryService.getById(i);
            ItemBatch itemBatch = itemBatchService.getById(inventory.getBatchId());
            itemBatch.setQcState(batchData.getQcState());
            itemBatchService.updateById(itemBatch);
        }
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "库存安全报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @PostMapping("/inventorySafetyReport")
    public Result inventorySafetyReport(@RequestBody InventoryCriteria criteria, @User CurrentUser user) {
        if (user == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
        }
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        return ResultGenerator.genSuccessResult(new PageInfo(inventoryService.inventorySafetyList(criteria)));
    }


    @ApiOperation(value = "查询待合并库存")
    @GetMapping("/palletsToCombine")
    public Result palletsToCombine(InventoryCriteria criteria, @User CurrentUser currentUser) {
//        if (currentUser == null) {
//            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
//        }
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        criteria.setMaxQuantity(1000.0);
        criteria.setMaxWeight(1000.0);
        List<Inventory> inventories = inventoryService.palletsToCombine(criteria);
        PageInfo pageInfo = new PageInfo(inventories);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/inventoriesWithBoxCode")
    public Result inventoriesWithBoxCode(String boxCode) {
        List<Inventory> inventories = inventoryService.inventoriesWithBoxCode(boxCode);
        PageInfo pageInfo = new PageInfo(inventories);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @PostMapping("/boxResult")
    @Transactional
    public Result boxResult(@RequestBody BoxResultInsertData insertData) {
        String boxCode = insertData.getBoxCode();
        String boxCode2 = insertData.getBoxCode2();
        List<Inventory> inventories = insertData.getInventoryList();
        List<Inventory> inventories2 = insertData.getInventoryList2();
        for (Inventory inventory : inventories) {
            inventory.setBoxCode(boxCode);
            inventoryService.updateById(inventory);
        }
        for (Inventory inventory : inventories2) {
            inventory.setBoxCode(boxCode2);
            inventoryService.updateById(inventory);
        }
        List<CombinePalletTask> tasks = combinePalletTaskService.taskWithBoxCode(boxCode);
        CombinePalletTask task = tasks.get(0);
        task.setCompleteTime(DateUtils.getNowDateTimeString());
        combinePalletTaskService.updateById(task);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/findGroupByWareOrgItem")
    @Transactional
    public Result boxResult(InventoryCriteria criteria) {
        List<GroupByWareOrgItem> list = inventoryService.findGroupByWareOrgItem(criteria);
        for (GroupByWareOrgItem groupByWareOrgItem : list) {

            List<PackDetail2> packDetailList = packDetailService.findByCode2(groupByWareOrgItem.getPackCode());

            groupByWareOrgItem.setPackDetails(packDetailList);
        }
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/canOut")
    @Transactional
    public Result canOut(InventoryCriteria criteria) {
        List<InventoryDto> list = inventoryService.canOut(criteria);

        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    private static Integer exportCount = 1;

    @GetMapping("/exportFindGroupByWareOrgItem")
    @Transactional
    public Result exportFindGroupByWareOrgItem(InventoryCriteria criteria) throws IOException {
        criteria.setPageNum(1);
        criteria.setPageSize(1000000);
        List<GroupByWareOrgItem> list = inventoryService.findGroupByWareOrgItem(criteria);
        String staticPath = fileSetting.getStaticFileDir();
        String downloadPath = File.separator + "download" + File.separator + "inventory" + ".xlsx";
        exportCount += 1;
        String filePath = staticPath + downloadPath;

        Workbook workbook = new SXSSFWorkbook();
        try {
            Sheet sheet = workbook.createSheet("First");
            sheet.createRow(0);
            FileOutputStream out = new FileOutputStream(filePath);
            workbook.write(out);

            String[] title = {"仓库", "货主", "物料", "料号", "总数", "分配数", "冻结数", "待上架数", "待发运数", "单位"};
            ExcelUtils excelUtils = new ExcelUtils(new File(filePath));
            excelUtils.writeArrayToExcel(0, true, 0, 0, title);

            for (int i = 0; i < list.size(); i++) {
                GroupByWareOrgItem box = list.get(i);
                String orgName = box.getOrganizationName() == null ? "" : box.getOrganizationName();
                String wareName = box.getWareName() == null ? "" : box.getWareName();
                String itemName = box.getItemName() == null ? "" : box.getItemName();
                String itemCode = box.getItemCode() == null ? "" : box.getItemCode();
                String totalQuantity = box.getTotalQuantity() == null ? "" : box.getTotalQuantity().toString();
                String totalAllotQuantity = box.getTotalAllotQuantity() == null ? "" : box.getTotalAllotQuantity().toString();
                String totalFreezeQuantity = box.getTotalFreezeQuantity() == null ? "" : box.getTotalFreezeQuantity().toString();
                String totalAcceptQuantity = box.getTotalAcceptQuantity() == null ? "" : box.getTotalAcceptQuantity().toString();
                String totalOutQuantity = box.getTotalOutQuantity() == null ? "" : box.getTotalOutQuantity().toString();
                String packDescribe = box.getPackDescribe() == null ? "" : box.getPackDescribe();

                String[] row = {orgName,
                        wareName,
                        itemName,
                        itemCode,
                        totalQuantity,
                        totalAllotQuantity,
                        totalFreezeQuantity,
                        totalAcceptQuantity,
                        totalOutQuantity,
                        packDescribe};
                excelUtils.insertRowWithFormat(0, i + 1);
                excelUtils.writeArrayToExcel(0, true, i + 1, 0, row);
            }
            excelUtils.writeAndClose();
            ((SXSSFWorkbook) workbook).dispose();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            workbook.close();
        }
        return ResultGenerator.genSuccessResult(downloadPath);

    }

    public void removeCell(Set<String> removeCell) {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper();
        queryWrapper.in("cell_code", removeCell);
        inventoryService.remove(queryWrapper);
    }

    /**
     * 生成唯一容器编码
     *
     * @return
     */
    public String generateCode() {
        //todo 导入ERP数据时容器编码重复查库会引起数据库缓慢 所以使用redis自增 如果使用当前日期会与mysql 库里的容器编码冲突,
        String db2 = RedisConstants.SOLE_CODE;
        String varietyNumber = "";
        ValueOperations<String, Integer> vo = redisTemplate.opsForValue();
        Integer number = vo.get(db2);
        if (number != null) {
            Long increment = redisTemplate.opsForValue().increment(db2, 1);
            varietyNumber = StringUtils.autoGenericCode(increment.toString(), 4);
        } else {
            vo.set(db2, 200);
            varietyNumber = StringUtils.autoGenericCode("1", 4);
        }
        StringBuilder sb = new StringBuilder();
        sb.append("CT");
        sb.append("-");
        sb.append("20220717");
        sb.append("-");
        sb.append(varietyNumber);
        return sb.toString();
    }


//    @PostMapping("inputCell")
//    public void inputCell(MultipartFile file) {
//        try {
//            Map<String, List<String>> map = Excel.returnExcelData(file.getInputStream(), file.getOriginalFilename());
//            List<String> shelfNames = new ArrayList<>();
//            map.forEach((key, val) -> {
//                shelfNames.add(val.get(0));
//            });
//            List<ShelfInfo> shelfInfos = insertShelf(shelfNames);
//            Map<String, List<ShelfInfo>> collect = shelfInfos.stream().collect(Collectors.groupingBy(ShelfInfo::getShelfName));
//            List<CellInfo> cellInfos = new ArrayList<>();
//            map.forEach((key, val) -> {
//                insertCell(val, collect, val.get(0), cellInfos);
//            });
////            cellNames.removeAll(shelfNames);
////            System.out.println(cellNames);
//
////            Map<String, List<ShelfInfo>> collect = shelfInfos.stream().collect(Collectors.groupingBy(ShelfInfo::getShelfName));
//            cellInfoService.saveBatch(cellInfos);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//    }

    public void insertCell(List<String> names, Map<String, List<ShelfInfo>> map, String shelfName, List<CellInfo> list) {
        Set<String> set = map.keySet();
        Set<String> collect = names.stream().filter(item -> !set.contains(item) && !"".equals(item)).collect(Collectors.toSet());
//        Set<String> collect = names.stream().filter(item -> set.contains(item)).collect(Collectors.toSet());
        for (String name : collect) {
            CellInfo cellInfo = new CellInfo();
            cellInfo.setCellCode(name);
            cellInfo.setCellName(name);
            if (ObjectUtil.isNotEmpty(map.get(shelfName))) {
                cellInfo.setShelfInfoId(map.get(shelfName).get(0).getShelfInfoId());

            }
            list.add(cellInfo);
        }
    }

    public List<ShelfInfo> insertShelf(List<String> shelfNames) {
        List<ShelfInfo> ShelfInfoList = shelfInfoService.list();
        //以前名称
        Set<String> oldShelfName = ShelfInfoList.stream().map(ShelfInfo::getShelfName).collect(Collectors.toSet());

        Set<String> newShelNames = shelfNames.stream().filter(item -> !oldShelfName.contains(item)).collect(Collectors.toSet());
        List<ShelfInfo> shelfInfoList = new ArrayList<>();
        for (String newShelName : newShelNames) {
            ShelfInfo shelfInfo = new ShelfInfo();
            shelfInfo.setShelfName(newShelName);
            shelfInfo.setType(1);
            shelfInfo.setShelfDescribe(newShelName);
            shelfInfo.setAreaId(543);
            shelfInfoList.add(shelfInfo);
        }
        if (ObjectUtil.isNotEmpty(shelfInfoList)) {
            shelfInfoService.saveBatch(shelfInfoList);
        }
        return shelfInfoService.list();
    }


    @GetMapping("setAreaInfo")
    public void setAreaInfo() {
        List<AreaInfo> list = areaInfoService.list();
        List<ShelfInfo> list2 = shelfInfoService.list();
        Map<String, List<AreaInfo>> collect = list.stream().collect(Collectors.groupingBy(AreaInfo::getAreaName));
        for (ShelfInfo shelfInfo : list2) {
            if (ObjectUtil.isNotEmpty(collect.get(shelfInfo.getShelfName()))) {
                shelfInfo.setAreaId(collect.get(shelfInfo.getShelfName()).get(0).getAreaId());
            }

        }

        shelfInfoService.updateBatchById(list2);
    }




}
